import cv2
from ultralytics import YOLO
from collections import defaultdict

# 加载YOLOv8模型
model = YOLO('yolov8n.pt')
# 打开视频文件
video_path = "images/008.mp4"
cap = cv2.VideoCapture(video_path)

# 遍历视频帧
total_detections = 0
class_counts = defaultdict(int)
# 遍历视频帧
while cap.isOpened():
    # 从视频中读取一帧
    success, frame = cap.read()
    if success:
        # 在该帧上运行YOLOv8推理
        results = model(frame)
        # 遍历检测结果和边界框
        for box in results[0].boxes:
            # 获取类别和置信度
            class_name = model.names[int(box.cls.item())]  # 类别名称
            confidence = float(box.conf)  # 置信度
            # 更新类别计数
            class_counts[class_name] += 1
            print(f"类别名称: {class_name}, 置信度: {confidence}")
        total_detections += len(results[0].boxes)

        # 在帧上可视化结果
        annotated_frame = results[0].plot()
        # 显示带注释的帧
        cv2.imshow("YOLOv8推理", annotated_frame)
        # 如果按下'q'则中断循环
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # 如果视频结束则中断循环
        break
# 计算每个类别的占比
class_percentages = {class_name: count / total_detections for class_name, count in class_counts.items()}
print("每个类别的占比:")
for class_name, percentage in class_percentages.items():
    print(f"{class_name}: {percentage:.2%}")
# 释放视频捕获对象并关闭显示窗口
cap.release()
cv2.destroyAllWindows()
